package com.hertz.iris.view;

import java.util.Collections;
import java.util.List;

import javax.inject.Inject;

import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.IntentFilter;
import android.net.ConnectivityManager;
import android.os.Bundle;
import android.os.OperationCanceledException;
import android.support.v4.content.Loader;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;

import com.github.kevinsawicki.http.HttpRequest.HttpRequestException;
import com.github.kevinsawicki.wishlist.SingleTypeAdapter;
import com.hertz.iris.Injector;
import com.hertz.iris.IrisServiceProvider;
import com.hertz.iris.R;
import com.hertz.iris.core.MatchAlarmService;
import com.hertz.iris.pojo.MatchAlarm;
import com.hertz.iris.pojo.MatchNba;
import com.hertz.iris.receiver.ConnectivyBroadcastReceiver;
import com.hertz.iris.ui.ItemListFragment;
import com.hertz.iris.ui.ThrowableLoader;
import com.hertz.iris.util.DateUtil;
import com.hertz.iris.util.Utils;

public class MatchsFragment extends ItemListFragment<MatchNba>{

	@Inject protected IrisServiceProvider serviceProvider;
	@Inject protected MatchAlarmService matchAlarmService;
	private LinearLayout networkBanner;
	
	private BroadcastReceiver connectivyBroadcastReceiver;
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        Injector.inject(this);
        
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
            Bundle savedInstanceState) {
    	View view = super.onCreateView(inflater, container, savedInstanceState);
    	networkBanner = (LinearLayout)view.findViewById(R.id.networkBanner);
    	if(Utils.checkNetwork(getActivity().getBaseContext())){
        	networkBanner.setVisibility(View.GONE);
        }else{
        	networkBanner.setVisibility(View.VISIBLE);
        }
    	connectivyBroadcastReceiver = new ConnectivyBroadcastReceiver(networkBanner);
        IntentFilter filter = new IntentFilter();  
        filter.addAction(ConnectivityManager.CONNECTIVITY_ACTION); 
        getActivity().registerReceiver(connectivyBroadcastReceiver, filter);
    	return view;
    }
    
    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);

        setEmptyText(R.string.no_match);


    }

    @Override
    protected void configureList(Activity activity, ListView listView) {
        super.configureList(activity, listView);

        listView.setFastScrollEnabled(true);
        listView.setDividerHeight(0);
        View header = activity.getLayoutInflater().inflate(R.layout.match_item_header, null);
        TextView ymd = (TextView)header.findViewById(R.id.ymd);
        int position = getArguments().getInt("addDay");
    	String ymdStr = DateUtil.getNextDay(position);
    	ymd.setText(ymdStr);
        getListAdapter().addHeader(header);
    }

    @Override
    public void onDestroyView() {
        setListAdapter(null);
        getActivity().unregisterReceiver(connectivyBroadcastReceiver);
        super.onDestroyView();
    }

    @Override
    public Loader<List<MatchNba>> onCreateLoader(int id, Bundle args) {
        final List<MatchNba> initialItems = items;
        return new ThrowableLoader<List<MatchNba>>(getActivity(), items) {

            @Override
            public List<MatchNba> loadData() throws Exception {
                try {
                    if(getActivity() != null) {
                    	int position = getArguments().getInt("addDay");
                    	String ymd = DateUtil.getNextDay(position);
                    	List<MatchAlarm> matchAlarms = matchAlarmService.getMatchAlarms(getActivity(),ymd);
                    	List<MatchNba> matchNbas = matchAlarmService.getMatchsNba(getActivity(),ymd);
                    	
                    	if(matchAlarms != null && matchAlarms.size() != 0){
                    		for(MatchNba matchNba : matchNbas){
                    			for(MatchAlarm ma : matchAlarms){
                    				if(matchNba.getId() == ma.getMid()){
                    					matchNba.setSubscribe(true);
                    					matchNba.setMatchAlarm(ma);
                    				}
                    			}
                    		}
                    	}
                        return matchNbas;
                    } else {
                        return Collections.emptyList();
                    }

                } catch (OperationCanceledException e) {
                    Activity activity = getActivity();
                    if (activity != null)
                        activity.finish();
                    return initialItems;
                }
            }
        };
    }

    public void onListItemClick(ListView l, View v, int position, long id) {
//    	NormalAlarm normalAlarm = ((NormalAlarm) l.getItemAtPosition(position));
//
//        startActivity(new Intent(getActivity(), NewsActivity.class).putExtra(NEWS_ITEM, normalAlarm));
    	
    }

    @Override
    protected int getErrorMessage(Exception exception) {
    	if(exception instanceof HttpRequestException){
    		return R.string.error_network;
    	}else
    		return R.string.error_loading_matchs;
    }

	@Override
	protected SingleTypeAdapter<MatchNba> createAdapter(
			List<MatchNba> items) {
		SingleTypeAdapter<MatchNba> adapter =  new MatchsListAdapter(getActivity(), items);
		return adapter;
	}
}

